package com.powernode.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.config.WhiteUrlsConfig;
import com.powernode.constant.AuthConstants;
import com.powernode.constant.BusinessEnum;
import com.powernode.constant.HttpConstants;
import com.powernode.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @create: 2024/7/15
 * @author: gyhe10
 * @description: 全局Token过滤器，约定token存放位置：header的Authorization字段中，token格式为：bearer token
 **/

@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    @Resource
    private WhiteUrlsConfig WhiteUrlsConfig;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 校验token
     * 1. 从上下文对象获取请求路径
     * 2. 根据配置文件白名单判断请求路径是否需要放行
     *      放行：不需要校验身份
     *      不放行：需要校验身份
     * @param exchange 上下文对象
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 从上下文对象获取请求路径
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求路径
        String path = request.getPath().value();
        // 2. 根据配置文件白名单判断请求路径是否需要放行
        if (WhiteUrlsConfig.getAllowUrls().contains(path)) {
            // 放行：不需要校验身份
            return chain.filter(exchange);
        } else {
            // 不放行：需要校验身份
            // 从请求头中约定好的位置获取token
            String authorizationValue = request.getHeaders().getFirst(AuthConstants.AUTHORIZATION);
            // 判断authorizationValue是否有值
            if (StringUtils.hasText(authorizationValue)) {
                // 从authorizationValue中获取token
                String tokenValue = authorizationValue.replaceFirst(AuthConstants.BEARER, "");
                // 判断token是否有值且是否在redis中存在
                // 约定在redis中保存token时的key格式为：login_token:token
                if (StringUtils.hasText(tokenValue) && stringRedisTemplate.hasKey(AuthConstants.LOGIN_TOKEN_PREFIX + tokenValue)) {
                    // 身份验证通过，放行
                    return chain.filter(exchange);
                }
            }
        }
        // 身份验证不通过或请求不合法，打印日志
        log.error("拦截非法请求，时间：{}，请求API路径：{}", new Date(), path);

        // 设置响应对象给客户，友好提示
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应头信息
        response.getHeaders().set(HttpConstants.CONTENT_TYPE, HttpConstants.APPLICATION_JSON);
        // 设置响应消息
        Result<Object> result = Result.fail(BusinessEnum.UNAUTHORIZED);

        // 创建一个ObjectMapper对象，将响应对象转换为json字符串
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
